package com.ly.hotel.spainterface.jyt;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ly.hotel.MyBaseActivity;
import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.spainterface.jyt.adapter.ConsumeCategoryAdapter;
import com.ly.hotel.spainterface.jyt.bean.MachineBean;
import com.ly.hotel.spainterface.jyt.bean.PluginBean;
import com.ly.hotel.spainterface.jyt.bean.consume.ConsumeBean;
import com.ly.hotel.spainterface.jyt.bean.consume.ConsumeCategory;
import com.ly.hotel.spainterface.jyt.bean.consume.ConsumeItem;
import com.ly.hotel.spainterface.jyt.bean.consume.ConsumeItemBean;
import com.ly.hotel.spainterface.jyt.utils.DataCallBack;
import com.ly.hotel.spainterface.jyt.utils.GsonUtils;
import com.ly.hotel.spainterface.jyt.utils.MachineUtils;
import com.ly.hotel.spainterface.jyt.utils.OkHttpUtils;
import com.ly.hotel.view.TitleLayout;
import com.squareup.okhttp.Request;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * Created by ThinkPad on 2018/3/17.
 */

public class JytXiaoFeiActivity extends MyBaseActivity implements DataCallBack {

    private static final String TAG = "JytXiaoFeiActivity";
    private String pluginVersion = "JYTv1.0.0";
    private static final int CONSUME_CATEGORY = 0;// 请求消费类别
    private static final int CONSUME_ITEM = 1;// 请求消费项目
    private PluginBean pluginBean = null;
    private MachineBean machineBean = null;
    private String serverIP = "";// 电视服务器ip
    private String serverPORT = "";// 电视服务器port

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jyt_xiaofei_activity);
        getMachineInfo();
        initTitle();
        getPluginConfig();
        getConsumeCategory();
    }

    // 获取电视相关信息
    public void getMachineInfo(){
        machineBean = MachineUtils.getHostAndTvInfo();
        if( machineBean != null){
            serverIP = machineBean.getServerIP();
            serverPORT = machineBean.getServerPORT();
            Log.i(TAG,"serverIP=" +  machineBean.getServerIP());
            Log.i(TAG,"serverPORT=" +  machineBean.getServerPORT());
            Log.i(TAG,"mac=" +  machineBean.getMac());
            Log.i(TAG,"categoryName=" +  machineBean.getCategoryName());
            Log.i(TAG,"tvName=" +  machineBean.getTvName());
        }
    }

    // 初始化标题栏
    public void initTitle(){
        TitleLayout titleLayout = findViewById(R.id.title_layout);
        TextView titleName = titleLayout.findViewById(R.id.activity_name);
        titleName.setTextColor(ContextCompat.getColor(this,R.color.mainWhite));
        titleName.setText("消费");
    }

    // 获得插件配置
    public void getPluginConfig(){
        Log.i(TAG,"pluginConfig=" + MyApplication.pluginCfg);
        Log.i(TAG,"interfaceVersion=" + MyApplication.interfaceVersion);
        if(pluginVersion.equals(MyApplication.interfaceVersion)){
            try{
                DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
                DocumentBuilder dombuilder = domfac.newDocumentBuilder();
                Document doc = dombuilder.parse(new ByteArrayInputStream(MyApplication.pluginCfg.getBytes("utf-8")));
                NodeList obj = doc.getElementsByTagName(MyApplication.interfaceVersion);
                pluginBean = new PluginBean();
                for (int i = 0; i < obj.getLength(); i++) {
                    NodeList sysList = ((Element) obj.item(i)).getElementsByTagName("xiaofei");
                    if (sysList.getLength() >= 1) {
                        NodeList headList = ((Element) sysList.item(0)).getElementsByTagName("ip");
                        if (headList.getLength() >= 1 && headList.item(0) != null) {
                            try {
                                String ip = headList.item(0).getFirstChild().getNodeValue().trim();
                                pluginBean.setIp(ip);
                                Log.i(TAG, "ip=" + ip);
                            } catch (NumberFormatException e) {
                                Toast.makeText(this, "ip配置有误！", Toast.LENGTH_SHORT).show();
                            }
                        }

                        headList = ((Element) sysList.item(0)).getElementsByTagName("port");
                        if (headList.getLength() >= 1 && headList.item(0) != null) {
                            try {
                                String port = headList.item(0).getFirstChild().getNodeValue().trim();
                                pluginBean.setPort(port);
                                Log.i(TAG, "port=" + port);
                            } catch (NumberFormatException e) {
                                Toast.makeText(this, "port配置有误！", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    // 请求数据大类数据
    public void getConsumeCategory(){
        String url = "http://" + serverIP + ":" + serverPORT + "/api/consume-category.json";
        OkHttpUtils.getAsynData(url,this,CONSUME_CATEGORY);
    }

    // 数据请求返回失败
    @Override
    public void requestFailure(Request request, IOException e, int requestCode) {
        if(requestCode == CONSUME_CATEGORY){
            Toast.makeText(this,"网络异常，无法请求到消费大类数据！",Toast.LENGTH_SHORT).show();
        }
    }

    // 数据请求返回成功
    @Override
    public void requestSuccess(String result, int requestCode) {
        Gson gson = new Gson();
        if(requestCode == CONSUME_CATEGORY){
            Log.d(TAG,"消费大类数据：" + result);
            ConsumeCategory consumeCategory = GsonUtils.parseSimpleJson(result,ConsumeCategory.class);
            if(consumeCategory.getCode() == 200 && !TextUtils.isEmpty(consumeCategory.getData())){
                List<ConsumeBean> consumeBeans = gson.fromJson(consumeCategory.getData(),
                        new TypeToken<List<ConsumeBean>>(){}.getType());
                if(consumeBeans.size() > 0){
                    initConsumeCategory(consumeBeans);
                }else{
                    Toast.makeText(this,"网络异常，无法请求到消费大类数据！",Toast.LENGTH_SHORT).show();
                }
            }
        }else if(requestCode == CONSUME_ITEM){
            Log.d(TAG,"消费项目数据：" + result);
            ConsumeItem consumeItem = GsonUtils.parseSimpleJson(result,ConsumeItem.class);
            if(consumeItem.getCode() == 200 && !TextUtils.isEmpty(consumeItem.getData())){
                List<ConsumeItemBean> consumeItemBeans = gson.fromJson(consumeItem.getData(),new TypeToken<List<ConsumeItemBean>>(){}.getType());
                /*for(int i = 0;i < consumeItemBeans.size();i ++){
                    ConsumeItemBean consumeItemBean = consumeItemBeans.get(i);
                    Log.d(TAG,consumeItemBean.getName());
                }*/
                if(consumeItemBeans.size() > 0){
                    initConsumeItem(consumeItemBeans);
                }else{
                    Toast.makeText(this,"网络异常，无法请求到消费大类数据！",Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    // 初始化消费大类
    public void initConsumeCategory(final List<ConsumeBean> consumeBeans){
        ListView consumeCategoryListView = findViewById(R.id.consume_category_listview);
        consumeCategoryListView.setVerticalScrollBarEnabled(false);
        final ConsumeCategoryAdapter mAdapter = new ConsumeCategoryAdapter(this,consumeBeans);
        consumeCategoryListView.setAdapter(mAdapter);
        consumeCategoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mAdapter.setDefaultPosition(position);
                ConsumeBean consumeBean = consumeBeans.get(position);
                if(consumeBean != null){
                    getConsumeItem(consumeBean.getId() + "");
                }
            }
        });
        // 默认点击第一项
        consumeCategoryListView.performItemClick(consumeCategoryListView.getChildAt(0),0,consumeCategoryListView.getItemIdAtPosition(0));
    }

    // 请求消费项目数据
    public void getConsumeItem(String cid){
        String url = "http://" + serverIP + ":" + serverPORT + "/api/consume.json" + "?cid=" + cid;
        OkHttpUtils.getAsynData(url,this,CONSUME_ITEM);
    }

    // 初始化消费项目
    public void initConsumeItem(List<ConsumeItemBean> consumeItemBeans){
        RecyclerView consumeItemRecyclerView = findViewById(R.id.consume_item_recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);

    }

}
